package com.xja.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author 周广瑞
 * @date 2022/4/12 10:31
 */
@Configuration
public class MySpringSecuityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;
    @Bean
    public PasswordEncoder createPasswordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //手动添加一些认证用户
        //,"login_manager"
//        auth.inMemoryAuthentication().withUser("zhangsan").password("1").roles("prod_manager")
//                .and().withUser("lisi").password("1").roles("user_manager");
        auth.userDetailsService(userDetailsService);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //未登录显示登录页面
        //http.formLogin()
        //配置自定义登录页面
        http.formLogin().loginPage("/login.html").loginProcessingUrl("/mylogin")
                .defaultSuccessUrl("/main.html").permitAll().and().csrf().disable();
        //添加拦截规则
        http.authorizeRequests()
                //以下资源不需要拦截验证
                .antMatchers("/","images/**","main.html").permitAll()
                //登录以后并且拥有user——manager角色可以访问user下资源
                .antMatchers("/user/**").hasRole("user_manager")
                .antMatchers("/prod/**").hasRole("prod_manager")
                //登录以后可以访问大部分资源
                .antMatchers("/**").authenticated();

        //配置安全退出路径
        http.logout().logoutUrl("/mylogout").logoutSuccessUrl("/login.html")
                .clearAuthentication(true).invalidateHttpSession(true);
            //无权限访问的页面
        http.exceptionHandling().accessDeniedPage("/403.html");
    }
}
